from django.db import models
from users.models import User
from restaurants.models import Restaurant, Dish


# Create your models here.

class Order(models.Model):
    STATUS_CHOICES = (
        ('pending', '待支付'),
        ('paid', '已支付'),
        ('preparing', '准备中'),
        ('delivering', '配送中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    )

    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='下单用户')
    restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, verbose_name='餐厅')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='订单状态')
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='总金额')
    delivery_address = models.TextField(verbose_name='配送地址')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '订单'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return f'订单{self.id} - {self.user.username}'


class OrderItem(models.Model):
    order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE, verbose_name='所属订单')
    dish = models.ForeignKey(Dish, on_delete=models.CASCADE, verbose_name='菜品')
    quantity = models.IntegerField(verbose_name='数量')
    price = models.DecimalField(max_digits=8, decimal_places=2, verbose_name='单价')

    class Meta:
        verbose_name = '订单项'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.dish.name} x {self.quantity}'


class Review(models.Model):
    order = models.OneToOneField(Order, on_delete=models.CASCADE, verbose_name='相关订单')
    rating = models.IntegerField(choices=[(i, i) for i in range(1, 6)], verbose_name='评分')
    comment = models.TextField(verbose_name='评价内容', blank=True)
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '评价'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f'{self.order.user.username}的评价'
